package com.lmj.learnspringboot.aop;

import com.lmj.learnspringboot.annotation.ResponseResult;
import com.lmj.learnspringboot.model.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: lmj
 * @version: ResponseResultHandler.java lmj v1.0 2021/8/8 01:50
 */

@Slf4j
@ControllerAdvice(basePackages = "com.lmj.learnspringboot.controller")
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

    private static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    /**
     * 判断是否要执行 beforeBodyWrite 方法，true为执行，false不执行，有注解标记的时候处理返回值
     *
     * @param returnType 参数
     * @param converterType type
     * @return 处理返回值
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        assert sra != null;
        HttpServletRequest request = sra.getRequest();
        ResponseResult responseResult = (ResponseResult)request.getAttribute(RESPONSE_RESULT_ANN);
        return responseResult != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectContentType,
        Class<? extends HttpMessageConverter<?>> selectConverterType, ServerHttpRequest request,
        ServerHttpResponse response) {
        log.info(" ENTER MSG .... Excuse");
        if (body instanceof Result) {
            return body;
        }
        return Result.success(body);
    }
}
